import router from './router'
import store from './store'
import { getToken } from '@/utils/auth'
import { Message } from 'element-ui'
import { removeToken } from '@/utils/auth'

const whiteList = ['/login', '/reg']

router.beforeEach((to, from, next) => {
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/home' })
    } else {
      next()
    }
  } else {
    // console.log('token不存在或已删除');
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
    }

  }

  // 以下代码进入了死循环
  // determine whether the user has logged in
  /*  const hasToken = getToken()
   if (hasToken) {
     if (to.path === '/login') {
       // if is logged in, redirect to the home page
       next({ path: '/home' })
     } else {
       const hasGetUserInfo = store.state.userinfo.username
       if (hasGetUserInfo) {
         next()
       } else {
         try {
           // get user info
           store.dispatch('getUserinfo')
           next({ ...to })
         } catch (error) {
           // remove token and go to login page to re-login
           removeToken()
           // localStorage.removeItem("vuex")
           Message.error(error || 'Has Error')
           next(`/login?redirect=${to.path}`)
         }
       }
     }
   } else {
     // console.log('token不存在或已删除');
     if (whiteList.indexOf(to.path) !== -1) {
       next()
     } else {
       // other pages that do not have permission to access are redirected to the login page.
       next(`/login?redirect=${to.path}`)
     }
 
   } */
})